﻿using System;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using HiTeachers.Services;
using HiTeachers.Services.Exceptions;

namespace HiTeachers.Web.Security
{
    /// <summary>
    /// custom membershipprovider for userlogin
    /// <membership defaultprovider="HiTeacherMembershipProvider">
    ///     <providers>
    ///         <add name="AgriMoreMembershipProvider"
    ///             type="HiTeachers.Web.Security.AgriMoreMembershipProvider"
    ///             dbProvider="System.Data.SqlClient"
    ///             connectionStringName="connstr"
    ///             requiresUniqueName="true"
    ///             cacheUserInfo="true"/>
    ///     </providers>
    /// </membership>
    /// </summary>
    public class HiTeacherMembershipProvider : MembershipProvider
    {
        private string applicationName;
        private readonly bool enablePasswordReset = false;
        private readonly bool enablePasswordRetrieval = false;
        private readonly int maxInvalidPasswordAttempts = 0;
        private readonly int minRequiredNonAlphanumericCharacters = 0;
        private readonly int minRequiredPasswordLength = 0;
        private string name;
        private readonly int passwordAttemptWindow = 0;
        private readonly MembershipPasswordFormat passwordFormat = new MembershipPasswordFormat();
        private readonly string passwordStrengthRegularExpression = string.Empty;
        private readonly bool requiresQuestionAndAnswer = false;
        private readonly bool requiresUniqueEmail = false;

        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
        /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception>
        /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            this.name = name;

            if (string.IsNullOrEmpty(name))
            {
                this.name = "HiTeacherMembershipProvider";
            }

            base.Initialize(name, config);
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            var user = TeacherServices.GetUser(username, password);
            if (user == null) return false;
            if (!user.IsVerified) throw new InActivateUserException("User is not activation!");

            var roles = user.Roles.Select(it => it.Name).ToArray();
            var userIdentity = new GenericIdentity(user.Email);
            var gp = new GenericPrincipal(userIdentity, roles);
            HttpContext.Current.User = gp;

            return true;
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordRetrieval
        {
            get { return enablePasswordRetrieval; }
        }

        public override bool EnablePasswordReset
        {
            get { return enablePasswordReset; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return requiresQuestionAndAnswer; }
        }

        public override string ApplicationName
        {
            get { return applicationName; }
            set { applicationName = value; }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return maxInvalidPasswordAttempts; }
        }

        public override int PasswordAttemptWindow
        {
            get { return passwordAttemptWindow; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return requiresUniqueEmail; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return passwordFormat; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return minRequiredPasswordLength; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return minRequiredNonAlphanumericCharacters; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return passwordStrengthRegularExpression; }
        }
    }
}
